/**  
 * All rights Reserved, Designed By www.flksh.com
 * @date:   2017-10-30 11:18:39   
 * @Copyright: 2013-2017 www.flksh.com Inc. All rights reserved. 
 * 注意：本内容仅限于上海福乐康社区养老服务有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.zx.cloud.service;

import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zx.cloud.domain.BlackEntity;
import com.zx.cloud.domain.Client;
import com.zx.cloud.domain.ClientAuth;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.ClientRisk;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.JDEntity;
import com.zx.cloud.domain.SMHMDDetail;
import com.zx.cloud.domain.SMJDData;
import com.zx.cloud.domain.SMJDDetail;
import com.zx.cloud.domain.SMJDEntity;
import com.zx.cloud.domain.VerifyEntity;
import com.zx.cloud.domain.VerifyMsg;
import com.zx.cloud.persistence.ClientAuthMapper;
import com.zx.cloud.persistence.ClientInfoMapper;
import com.zx.cloud.persistence.ClientMapper;
import com.zx.cloud.persistence.ClientRiskMapper;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;
import com.zx.cloud.util.HttpUtils;
import com.zx.cloud.util.MessageVerificationUtils;

/**
 * 
 */
@Service
public class VerifyMsgService extends CrudServiceImpl<VerifyMsg>{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(VerifyMsgService.class);
    
    @Autowired
    private ClientAuthMapper clientAuthMapper;
    
    @Autowired
    private ClientInfoMapper clientInfoMapper;
    
	@Autowired
	private DictMapper dictMapper;
	
	@Autowired
    private ClientMapper clientMapper;
	
	@Autowired
    private ClientInfoService clientInfoService;
	@Autowired
	 private ClientRiskMapper clientRiskMapper;
    
  	@Autowired
    public VerifyMsgService(CrudMapper<VerifyMsg> mapper) {
        super(mapper);
    }
  	
  	public String handleCheckLiveness(String filePath, String fileUrl, String fileId){
  		
  		String resultStatus = null;
  		
  		String resultResponse = MessageVerificationUtils.checkLiveness(filePath, fileUrl, fileId);
  		
  		if(StringUtils.isNotEmpty(resultResponse)){
  			
  			JsonObject jsonObject = new JsonParser().parse(resultResponse).getAsJsonObject();
  			
  			String status = jsonObject.get("status").getAsString();
			resultStatus = status;
  		}
  		
  		return resultStatus;
  	}

  	public String handleVerification(String filePath, Long userId){
  		
  		String resultStatus = null;
  		
  		Map<String, Object> params = new HashMap<String, Object>();
  		
  		/*
		 * 获取数据库OCR接口相关配置
		 */
		Dict dict = new Dict();
		dict.setParentCode("LF0001");
		List<Dict> dicts = dictMapper.getDitByParentCode(dict);
		if(null != dicts && dicts.size() > 0){
			for(int i = 0; i < dicts.size(); i++){
				params.put(dicts.get(i).getName(), dicts.get(i).getValue());
			}
		}
		
		String resultResponse = MessageVerificationUtils.parseIdcardOcrResult(params, filePath);
		
		if(StringUtils.isNotEmpty(resultResponse)){
			
			JsonObject jsonObject = new JsonParser().parse(resultResponse).getAsJsonObject();
			
			String status = jsonObject.get("status").getAsString();
			resultStatus = status;
			
			ClientAuth clientAuth = clientAuthMapper.findByClientID(userId); //认证信息
			
			ClientInfo clientInfo = clientInfoMapper.findClientById(userId); //详细信息
			
			LOGGER.info("*******************************获取接口返回状态码："+ status +"************************************");
			
			if("OK".equals(status)){
				
				VerifyMsg verifyMsg = new VerifyMsg();
				
				String info = jsonObject.get("info").getAsString();
				JsonObject infoJson = new JsonParser().parse(info).getAsJsonObject();
				
				String name = infoJson.get("name").getAsString();
				JsonObject nameJson = new JsonParser().parse(name).getAsJsonObject();
				verifyMsg.setName(nameJson.get("text").getAsString());
				clientInfo.setRealName(nameJson.get("text").getAsString());
				
				String sex = infoJson.get("sex").getAsString();
				JsonObject sexJson = new JsonParser().parse(sex).getAsJsonObject();
				verifyMsg.setSex(sexJson.get("text").getAsString());
				clientInfo.setSex(sexJson.get("text").getAsString());
				
				String nation = infoJson.get("nation").getAsString();
				JsonObject nationJson = new JsonParser().parse(nation).getAsJsonObject();
				verifyMsg.setNation(nationJson.get("text").getAsString());
				clientInfo.setNational(nationJson.get("text").getAsString());
				
				String year = infoJson.get("year").getAsString();
				JsonObject yearJson = new JsonParser().parse(year).getAsJsonObject();
				verifyMsg.setYear(yearJson.get("text").getAsString());
				
				String month = infoJson.get("month").getAsString();
				JsonObject monthJson = new JsonParser().parse(month).getAsJsonObject();
				verifyMsg.setMonth(monthJson.get("text").getAsString());
				
				String day = infoJson.get("day").getAsString();
				JsonObject dayJson = new JsonParser().parse(day).getAsJsonObject();
				verifyMsg.setDay(dayJson.get("text").getAsString());
				
				String address = infoJson.get("address").getAsString();
				JsonObject addressJson = new JsonParser().parse(address).getAsJsonObject();
				verifyMsg.setAddress(addressJson.get("text").getAsString());
				clientInfo.setIdAddr(addressJson.get("text").getAsString());
				
				String idNum = infoJson.get("idNum").getAsString();
				JsonObject idNumJson = new JsonParser().parse(idNum).getAsJsonObject();
				verifyMsg.setIdnum(idNumJson.get("text").getAsString());
				clientInfo.setId(new Long(idNumJson.get("text").getAsString()));
				
				String authority = infoJson.get("authority").getAsString();
				JsonObject authorityJson = new JsonParser().parse(authority).getAsJsonObject();
				verifyMsg.setAuthority(authorityJson.get("text").getAsString());
				
				String validity = infoJson.get("validity").getAsString();
				JsonObject validityJson = new JsonParser().parse(validity).getAsJsonObject();
				verifyMsg.setValidity(validityJson.get("text").getAsString());
				
				verifyMsg.setCreateDate(OffsetDateTime.now());
				verifyMsg.setRemark(userId+"");
				
				LOGGER.info("*******************************保存ocr接口返回数据入库************************************");
				super.insert(verifyMsg);
				
				if(null != clientAuth){
					clientAuth.setIdState(1); //认证成功
				}
				
				clientInfo.setUpdateTime(OffsetDateTime.now());
				clientInfoMapper.update(clientInfo);
			}else{
				if(null != clientAuth){
					clientAuth.setIdState(2); //认证失败
				}
			}
			
			clientAuth.setIdTime(OffsetDateTime.now());
			clientAuthMapper.update(clientAuth);
		}
  		
  		return resultStatus;
  	}
  	/**
  	 * @Description:同盾校验
  	 */
  	public int handlePreLoanMsg(Long userId, VerifyMsg verifyMsg){
  		 int resultInt = 1;
		 VerifyEntity verifyEntity = new VerifyEntity();
  		 verifyEntity.setName(verifyMsg.getName());
  		 verifyEntity.setId_number(verifyMsg.getIdnum());
		 if(null != userId){
  			ClientInfo clientInfo = clientInfoMapper.findClientById(userId);
  	  		if(null != clientInfo){
  	  			verifyEntity.setMobile(clientInfo.getPhone());
  	  		   }
  	  		}
  		String url_step1 = null;
  		String url_step2 = null;
  		
  		Dict dict = new Dict();
		dict.setParentCode("PRELOAN");
		List<Dict> dicts = dictMapper.getDitByParentCode(dict);
		
		if(null != dicts && dicts.size() > 0){
			for(Dict tmp : dicts){
				if("url_step1".equals(tmp.getName())){
					url_step1 = tmp.getValue();
				}
				if("url_step2".equals(tmp.getName())){
					url_step2 = tmp.getValue();
				}
			}
		}
  		
		String body = "name=" + verifyEntity.getName() + "&id_number="+ verifyEntity.getId_number()+ "&mobile=" + verifyEntity.getMobile() + "";
  		String response = HttpUtils.sentPost(url_step1, body);
  		
  		if(StringUtils.isNotEmpty(response)){
  			JSONObject json = new JSONObject(response);
  			Boolean success = json.getBoolean("success");
  			if(success){
  				String reportId = json.getString("report_id");
  				resultInt = queryPreLoanResult(verifyEntity, url_step2, reportId);
  			}
  		}
  		
  		return resultInt;
  	}
  	/**
  	 * @Description:处理同盾校验响应数据
  	 */
  	public int queryPreLoanResult(VerifyEntity verifyEntity, String url, String reportId){
  		int result = 0;
  		
  		url = url +"&report_id="+reportId;
  		
  		String response = HttpUtils.doGet(url, null, 3, 10, "UTF-8");
  		
  		if(StringUtils.isNotEmpty(response)){
  			if(response.contains("black_list")){ //命中黑名单
  				Client client = clientMapper.findLoginNameExist(verifyEntity.getMobile());
  				if(null != client){
  					ClientInfo clientInfo = clientInfoMapper.findClientById(client.getId());
  					clientInfo.setType(0);
  					
  					if(StringUtils.isNotBlank(clientInfo.getBlackReason())){
  						clientInfo.setBlackReason(clientInfo.getBlackReason()+"+同盾命中黑名单");
  					}
  					clientInfo.setBlackReason("同盾命中黑名单");
  					//修改
  					clientInfoService.update(clientInfo);
  				}
  			}
  			JSONObject json = new JSONObject(response);
  			Boolean success = json.getBoolean("success");
  			if(success){
  				JSONArray platform = json.getJSONArray("risk_items");
  				List<String> thisList = new ArrayList<String>();
  				if(null != platform && platform.length() > 0){
  					for(int i = 0; i < platform.length(); i ++){
  						JSONObject jsonObject = platform.getJSONObject(i);
  						String thisString = jsonObject.toString();
  						if(StringUtils.isNotEmpty(thisString) && thisString.contains("platform_detail_dimension")){
  							thisList.add(thisString);
  						}
  					}
  				}
  				
  				List<String> dataList = new ArrayList<String>();
  				if(null != thisList && thisList.size() > 0){
  					for(int i = 0; i < thisList.size(); i ++){
  						JSONObject thisJson = new JSONObject(thisList.get(i));
  						String item_name = thisJson.getString("item_name");
  						if(item_name.contains("7天内") || item_name.contains("1个月内")){
  							dataList.add(thisJson.toString());
  						}
  					}
  				}
  				
  				boolean days7 = false;
  				boolean days30 = false;
  				if(null != dataList && dataList.size() > 0){
  					for(int i = 0; i < dataList.size(); i ++){
  						JSONObject dataJson = new JSONObject(dataList.get(i));
  						String item_name = dataJson.getString("item_name");
  						if(item_name.contains("7天内")){
  							JSONObject item_detail = dataJson.getJSONObject("item_detail");
  							int platform_count = item_detail.getInt("platform_count");
  							if(platform_count >= 7){
  								days7 = true;
  							}
  						}
  						if(item_name.contains("1个月内")){
  							JSONObject item_detail = dataJson.getJSONObject("item_detail");
  							int platform_count = item_detail.getInt("platform_count");
  							if(platform_count >= 20){
  								days30 = true;
  							}
  						}
  					}
  				}
  				
  				if(days7 || days30){ //一周7次或者一个月20次借贷 算多头借贷
  					Client client = clientMapper.findLoginNameExist(verifyEntity.getMobile());
  	  				if(null != client){
  	  					ClientInfo clientInfo = clientInfoMapper.findClientById(client.getId());
  	  					clientInfo.setBorrow(0);
  	  					//修改
  	  					clientInfoService.update(clientInfo);
  	  				}
  				}
  			}
  		}
  		
  		return result;
  	}
    /**
     * @Description:数美校验
     */
	public int   handlePreLoanMsgByShuMei( Long userId, VerifyMsg verifyMsg) {
		VerifyEntity verifyEntity = new VerifyEntity();
  		verifyEntity.setName(verifyMsg.getName());
  		verifyEntity.setId_number(verifyMsg.getIdnum());
		if(null != userId){
  			ClientInfo clientInfo = clientInfoMapper.findClientById(userId);
  	  		if(null != clientInfo){
  	  			verifyEntity.setMobile(clientInfo.getPhone());
  	  		   }
  	  		}
		
		LOGGER.info("*******************************数美借贷接口+数美黑名单接口************************************");
        int resultInt = 1;
        String url_jd = null;
  		String url_hmd = null;
  		String sm_accessKey = null;
  		
  		Dict dict = new Dict();
		dict.setParentCode("SHUMEI");
		List<Dict> dicts = dictMapper.getDitByParentCode(dict);
		if(null != dicts && dicts.size() > 0){
			for(Dict tmp : dicts){
				if("url_jd".equals(tmp.getName())){
					url_jd = tmp.getValue();
				}
				if("url_hmd".equals(tmp.getName())){
					url_hmd = tmp.getValue();
				}
				if("sm_accessKey".equals(tmp.getName())){
					sm_accessKey = tmp.getValue();
				}
			}
		}
			SMJDData data = new SMJDData();
			data.setPhone(verifyEntity.getMobile());
			data.setName(verifyEntity.getName());
			data.setPrcid(verifyEntity.getId_number());
			
			SMJDEntity smjd = new SMJDEntity();
			smjd.setData(data);
			smjd.setAccessKey(sm_accessKey);
			
			JDEntity sMJDDetail = new JDEntity();
			BlackEntity sMHMDDetail = new BlackEntity();
			
			   String resjdJson = null;
			   String reshmdJson = null;
				// 数美借贷接口
			    Gson gson = new Gson();
				resjdJson = HttpUtils.doPost(url_jd, gson.toJson(smjd),null, 3, 10, "utf-8");
				LOGGER.info("#doPost() 数美借贷接口返回信息：" + resjdJson);
				sMJDDetail = (JDEntity) gson.fromJson(resjdJson, JDEntity.class);
				//保存风控数据-多头借贷
				ClientRisk  clientRisk=new ClientRisk();
				clientRisk.setClientId(userId);		
				clientRisk.setRiskChannel(2);//数美
				clientRisk.setRiskType(2);//多头借贷
				SMJDDetail   detail=sMJDDetail.getDetail();
				JSONObject jObject=new JSONObject(detail);
				clientRisk.setRiskDetail(jObject.toString());
				clientRisk.setCreateTime(OffsetDateTime.now());
				clientRiskMapper.insert(clientRisk);
				
				// 数美黑名单接口
				reshmdJson = HttpUtils.doPost(url_hmd, gson.toJson(smjd),null, 3, 10, "utf-8");
				LOGGER.info("#doPost() 数美黑名单接口返回信息：" + reshmdJson);
				sMHMDDetail = (BlackEntity) gson.fromJson(reshmdJson, BlackEntity.class);
				
				handleShuMeiData(sMJDDetail,  sMHMDDetail,verifyEntity );
				
				return  resultInt;
	}
  /**
   * @Description:处理数美的黑名单、多头借贷的响应数据
   */
	private void handleShuMeiData(JDEntity jDEntity, BlackEntity black,  VerifyEntity verifyEntity) {
		Gson gson = new Gson();
		if (!gson.toJson(black).equals("{}")) {
			// 黑名单
			if ((StringUtils.isNotBlank(black.getDetail().getIn_black())) && (black.getDetail().getIn_black().equals("1"))) {
				LOGGER.info("#verify() 命中黑名单：{}" + verifyEntity.getId_number());
				
				Client client = clientMapper.findLoginNameExist(verifyEntity.getMobile());
  				if(null != client){
  					ClientInfo clientInfo = clientInfoMapper.findClientById(client.getId());
  					clientInfo.setType(0);
  					if(StringUtils.isNotBlank(clientInfo.getBlackReason())){
  						clientInfo.setBlackReason(clientInfo.getBlackReason()+"+数美命中黑名单");
  					}
  					clientInfo.setBlackReason("数美命中黑名单");
  					//修改
  					clientInfoService.update(clientInfo);
  				}
			}
			// 多头借贷
			if (Integer.parseInt(jDEntity.getDetail().getItfin_registers()) > 1) {
				LOGGER.info("#verify() 命中多头借贷：{}" + verifyEntity.getId_number());
				Client client = clientMapper.findLoginNameExist(verifyEntity.getMobile());
	  			if(null != client){
	  					ClientInfo clientInfo = clientInfoMapper.findClientById(client.getId());
	  					clientInfo.setBorrow(0);
	  					//修改
	  					clientInfoService.update(clientInfo);
	  				}
			}

		}
		
	}

}
